package cc.momas.momall.search.dao;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cc.momas.common.vo.SearchItem;
import cc.momas.common.vo.SearchResult;

/**
 * 商品搜索的DAO
 * @author sod
 *
 */
@Repository
public class SearchDao {

	@Autowired
	private SolrServer solrServer;
	
	public SearchResult search(SolrQuery query) throws Exception{
		//根据query查询数据库
		QueryResponse queryResponse  = solrServer.query(query);
		//取查询结果
		SolrDocumentList documentList = queryResponse.getResults();
		//查询结果总记录数
		long numFound = documentList.getNumFound();
		SearchResult result = new SearchResult();
		result.setRecordCount(numFound);
		//取商品列表,需要取高亮显示
		Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
		List<SearchItem> itemList = new LinkedList<>();
		for (SolrDocument solrDocument : documentList) {
			SearchItem item = new SearchItem();
			item.setId(String.valueOf(solrDocument.get("id")));
			
			item.setCategory_name((String) solrDocument.get("product_catalog_name"));
			item.setImage((String) solrDocument.get("product_picture"));
			item.setPrice((float) solrDocument.get("product_price"));
			item.setSell_point((String) solrDocument.get("product_sell_point"));
			//读取高亮显示
			List<String> list = highlighting.get(solrDocument.get("id")).get("product_name");
			String title = "";
			if(list != null && list.size() > 0) {
				title = list.get(0);
			} else {
				title = (String) solrDocument.get("product_name");
			}
			item.setTitle(title);
			//添加到商品列表
			itemList.add(item);
		}
		result.setItemList(itemList);
		return result;
	}
	
}
